package com.shr.xsunmvc.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;

public class PathUtils {

	public static final String VAR_REGEX = ":(\\w+)";;
	public static final String REPLACE = "([^#/?]+)";
	private static final String SLASH = "/";

	/**
	 * 处理path为空，开头没有"/"和最后多了"/"的情况
	 * @param path
	 * @return
	 */
	public static String fixPath(String path) {
		if(path == null)
			return "/" ;
		if(!path.startsWith("/"))
			path = "/" + path ;
		if(path.length() > 1 && path.endsWith("/"))
			return path.substring(0, path.length() - 1) ;
		return path ;
	}

	
	/**
	 * 获取先对路径
	 * @param request
	 * @return
	 */
	public static String getRelativePath(HttpServletRequest request) {
		String path = request.getRequestURI() ;
		String contextPath = request.getContextPath() ;
		
		path = path.substring(contextPath.length()) ;
		
		if(path.length() > 1)
			path = path.substring(1) ;
		
		if(!path.startsWith(SLASH))
			path = SLASH + path ;
		try {
			path = URLDecoder.decode(path, "UTF-8") ;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		return path;
	}

}
